package xiaohui

import (
	"fmt"
	"strconv"
	"strings"
)

// 两个大整数（正数）相加，int64都无法存储的那种

func BigNumberSum(numA, numB string) string {
	// 1 把两个大整数用数组逆序存储，数组长度等于较大整数位数+1
	var maxLength = len(numA)
	if len(numB) > maxLength {
		maxLength = len(numB)
	}
	// 逆序存储
	arrayA := make([]int, maxLength+1)
	for i, k := len(numA)-1, 0; i >= 0; i-- {
		arrayA[k], _ = strconv.Atoi(string(numA[i]))
		k++
	}
	fmt.Println("arrayA ==", arrayA)
	arrayB := make([]int, maxLength+1)
	for i, k := len(numB)-1, 0; i >= 0; i-- {
		arrayB[k], _ = strconv.Atoi(string(numB[i]))
		k++
	}
	fmt.Println("arrayB ==", arrayB)
	// 2 构建result数组，数组长度等于较大整数位数+1
	result := make([]int, maxLength+1)
	// 3 遍历数组，按位相加
	for i := 0; i < len(result); i++ {
		tmp := result[i]
		tmp += arrayA[i]
		tmp += arrayB[i]
		// 判断是否进位
		if tmp >= 10 {
			tmp = tmp - 10
			result[i+1] = 1
		}
		result[i] = tmp
	}
	fmt.Println("result ==", result)
	// 4 把result数组再次逆序并转为string
	sb := strings.Builder{}
	findFirst := false
	for i := len(result) - 1; i >= 0; i-- {
		if !findFirst {
			if result[i] == 0 {
				continue
			}
			findFirst = true
		}
		sb.WriteString(strconv.Itoa(result[i]))
	}

	return sb.String()
}
